"""
Copyright (c) 2023 - present SKbioinfo
"""

from flask_restful import Resource, reqparse,fields, marshal_with
from flask import request
from flask import jsonify
from flask_login import login_required,current_user

from apps import db
from apps.NGS_API.utils.log_helper import lg
from apps.NGS_API.user.db_user import *
from apps.NGS_API.connector.db_common import *
from apps.authentication.models import Users
import time

'''
    User infos.NGS_API 
'''

user = {
            'id': fields.Integer,
            'username': fields.String,
            'email': fields.String,
            'create_time': fields.String,
            'role_id': fields.String
}

class interfaceUser(Resource):
    @login_required
    def get(self):
        try:
            user={}
            user_base_info = get_user_info(user=current_user.username)
            user_infos = []
            for suser in user_base_info:
                if suser[2] in ["R990","R100","R200"]:
                    next
                else:
                    user_infos.append(
                        {
                            "id": suser[0],
                            "username": suser[1],
                            "role_id": suser[2],
                            "email": suser[3],
                            "create_time": suser[4],
                            "role_detail": suser[5],
                            "role_permissions": suser[6],
                            "group": suser[7],
                            "flag": False
                        }
                    )
            user["user_infos"] = user_infos
            response=jsonify(user)
            response.status_code = 202
            return response
        except Exception as e:
            lg.error(e)        
    
    @login_required
    def post(self):
        ### set reqparser params ###
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('username',type=str,help='用户名验证错误！',required=True,trim=True) 
            parser.add_argument('password', type=str, help='密码验证错误！',required=True,default="12345") 
            parser.add_argument('role_id',type=str, required=True,help='用户身份验证错误！')
            parser.add_argument('email',type=str,required=True,help="用户邮箱错误！")
            args=parser.parse_args(strict=True)
            ### user database commit  ###
            user=Users(**args)
            user.create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
            db.session.add(user)
            db.session.commit()
            ### record response ###
            response=jsonify(
                status=202,
                msg="pass"
            )
            return response
        except Exception as e:
            lg.error(e)
            response = jsonify(
                status=404,
                msg=e.args[0],
            )
            return response
        
class interfaceUserID(Resource):
    @login_required
    def get(self,id):
        return id

    @login_required
    def delete(self,id):
        try:
            if request.data.decode(encoding='UTF-8',errors='strict') == "-1":
                pass
            else:
                delete_sql = "DELETE FROM {table_name} WHERE {db_name} = \"{col_value}\"".format(
                    table_name="users",
                    col_value=id,
                    db_name="id"
                )
                delete_info(delete_sql=delete_sql)
                return id
        except Exception as e:
            lg.error(e)
    
    @login_required    
    def post(self,id):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument("id",type=str,help="ID输入错误！",required=True)
            args=parser.parse_args(strict=True)
            delete_sql = "DELETE FROM {table_name} WHERE {db_name} =\"{col_value}\"".format(
                table_name="users",
                col_value=args.get("id"),
                db_name="id"
            )
            delete_info(delete_sql=delete_sql)
        except Exception as e:
            lg.error(e)
            
    def put(self,id):
        try:
            if request.data.decode(encoding='UTF-8',errors='strict') == "-1":
                pass
            else:
                parser = reqparse.RequestParser()
                parser.add_argument('id',type=str, help="用户ID输入错误！",required=True)
                parser.add_argument('username',type=str,help='用户名验证错误！',required=True,trim=True) 
                parser.add_argument('role_id',type=str, required=True,help='用户身份验证错误！')
                parser.add_argument('email',type=str,required=True,help="用户邮箱错误！")
                args=parser.parse_args(strict=True)
                user_update_sql="""
                UPDATE {table_name} SET 
                    username=\"{username}\",
                    email=\"{email}\",
                    role_id=\"{role_id}\"            
                WHERE id=\"{id}\"
                """.format(
                        table_name="users",
                        username=args.get("username"),
                        email=args.get("email"),
                        role_id=args.get("role_id"),
                        id=args.get("id")
                )
                update_info(update_sql=user_update_sql)
                return id
        except Exception as e:
            lg.error(e)
            
class interfaceUsergroup(Resource):
    @login_required
    def get(self,group):
        try:
            print(group)
        except Exception as e:
            lg.error(str(e))